<template>
  <div class="flex items-center gap-4">
    <button class="flex items-center gap-1 text-gray-600 hover:text-gray-900" @click="$router.push('/identity')">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <!-- 人像轮廓图标 -->
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 12a4 4 0 100-8 4 4 0 000 8z" />
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 20c0-2.667 3.333-4 8-4s8 1.333 8 4" />
      </svg>
      <span>身份切换</span>
    </button>

    <button class="relative flex items-center gap-1 text-gray-600 hover:text-gray-900" @click="$router.push('/messages')">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h6m-6 4h8"/>
      </svg>
      <span>消息</span>
    </button>

    <button class="flex items-center gap-1 text-gray-600 hover:text-gray-900" @click="logout">
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/>
      </svg>
      <span>退出</span>
    </button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HeaderActions',
  data() {
    return {
      unread: 0,
      timer: null
    }
  },
  methods: {
    async fetchUnread() {
      const userId = Number(localStorage.getItem('userId'))
      if (!userId) {
        this.unread = 0
        return
      }
      try {
        const { data } = await axios.get('/api/messages/unread-count', { params: { userId } })
        this.unread = (data && data.data && data.data.unread) || 0
      } catch (e) {
        // 忽略未读数错误，保持上次值
      }
    },
    logout() {
      localStorage.removeItem('userToken')
      this.$router.push('/login')
    }
  },
  mounted() {
    this.fetchUnread()
    this.timer = setInterval(this.fetchUnread, 10000)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>
